﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Apollo;
using System.Web.Security;
using System.DirectoryServices.AccountManagement;
using System.Configuration;
using NHibernate;


namespace Apollo.Website
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonLogin_Click(object sender, EventArgs e)
        {
            User user = Apollo.Application.CurrentSession.QueryOver<User>()
                .Where(u => u.Name == TextBoxUsername.Text)
                .SingleOrDefault();

            if (user != null)
            {
                
                if (user.AuthenticationType == "ActiveDirectory")
                {
                    PrincipalContext ldapContext = new PrincipalContext(
                        ContextType.Domain,
                        Apollo.Application.ConfigurationSection.Apollo.LDAP.Server,
                        Apollo.Application.ConfigurationSection.Apollo.LDAP.Filter
                    );

                    if (ldapContext.ValidateCredentials(user.Name, TextBoxPassword.Text))
                    {
                        LoginUser(user);
                    }
                    else
                    {
                        ldapContext = new PrincipalContext(ContextType.Domain);
                        UserPrincipal foundUser = UserPrincipal.FindByIdentity(ldapContext, user.Name);

                        if (foundUser != null)
                        {
                            if (foundUser.PasswordNeverExpires)
                            {
                                LabelWarn.Text = "Parola este gresita!";
                            }
                            else if (foundUser.AccountLockoutTime != null)
                            {
                                LabelWarn.Text = "Cont blocat din data de " + foundUser.AccountLockoutTime.ToString();
                            }
                            else if (foundUser.AccountExpirationDate != null && foundUser.AccountExpirationDate < DateTime.Now)
                            {
                                LabelWarn.Text = "Cont expirat";
                            }
                            else
                            {
                                LabelWarn.Text = "Parola gresita!";
                            }
                        }
                        else
                        {
                            LabelWarn.Text = "Utilizator inexistent in LDAP!";
                        }
                        LabelWarn.Visible = true;
                    }
                }
                else
                {
                    if (user.Password == FormsAuthentication.HashPasswordForStoringInConfigFile(TextBoxPassword.Text, "MD5"))
                        LoginUser(user);
                    else
                    {
                        LabelWarn.Text = "Parola este incorecta!";
                        LabelWarn.Visible = true;
                    }
                }
            }
            else {
                LabelWarn.Text = "Utilizatorul '{0}' nu a fost gasit in sistem!".Replace("{0}", TextBoxUsername.Text);
                LabelWarn.Visible = true;
            }
        }

        protected void LoginUser(User user)
        {

            ITransaction tran = Apollo.Application.CurrentSession.BeginTransaction();
            try
            {
                user.LastLoginDate = DateTime.Now;

                Apollo.Application.CurrentSession.Save(user);

                tran.Commit();
            }
            catch
            {
                tran.Rollback();
            }

            //FormsAuthentication.RedirectFromLoginPage(user.Name, true);
            FormsAuthentication.RedirectFromLoginPage(user.Name, CheckBoxRememberMe.Checked);
        }
    }
}